package ks.server.persist;

import java.net.URL;
import java.util.Collection;

import ks.managers.plugin.Plugin;
import ks.managers.plugin.PluginManager;

/**
 * Provides local storage of plugins
 * @author Harry Moreno
 * @author Jen_Hunt
 *
 */
public class PersistentPluginManager extends PluginManager {
	
	/** Protect access to this constructor. */
	public PersistentPluginManager() {
		super();
		
		initialize();
	}

	private void initialize() {
		try {
			Collection<Plugin> plugins = Database.getPlugins();
			for (Plugin pl : plugins) {
				knownPlugins.put(pl.name, pl);
			}
		} catch (Exception e) {
			System.err.println("Unable to populate from db");
		}
	}
	
	/**
	 * Adds the given Plugin by name and URL to be associated with that plugin.
	 * <p>
	 * 
	 * @param pluginName
	 * @param url
	 */
	public boolean add (String pluginName, URL url) {
		
		// try to add to DB
		try {
			if (!Database.addPlugin(pluginName, url.toString())) {
				System.err.println("Unable to add plugin to persistent database");
				return false;
			}
			
			super.add(pluginName, url);
		} catch (Exception e1) {
			System.err.println("Unable to add plugin to persistent database: " + pluginName);
			return false;
		}

		// done
		return true;
	}
	
	/**
	 * Remove user from the store of users.
	 * 
	 * @param u The User to remove from the store of users.
	 * @return true on success. false on failure.
	 */
	public boolean remove (Plugin p) {
		try {
			if (!Database.deletePlugin(p.getName())) {
				System.err.println("Unable to remove plugin from persistent database.");
				return false;
			}
			
			super.remove(p.getName());
		} catch (Exception e1) {
			System.err.println("Unable to remove plugin from persistent database: " + p.getName());
			return false;
		}
		
		return true;
	}
	
	public boolean updatePlugin (String name) {
		try {
			if (!Database.updatePlugin(super.getPlugin(name))) {
				System.err.println("Unable to update plugin: " + name);
				return false;
			}
		} catch (Exception e) {
			System.err.println("Unable to update user in persistent database: " + name);
			return false;
		}
		
		return true;
	}
	
}
